package com.cw.starter.sharding.util;

/**
 * 获取分片键
 *
 * @author chenw
 * @date 2021/11/4
 */
public class SplitKeyGenerateUtil {
    /**
     * 获取分片键
     *
     * @param splitKeyVal 分片键值
     * @param subTableCount 分表数量
     */
    public static Long getSplitKey(Object splitKeyVal, Integer subTableCount) {
        long hashVal = splitKeyVal.toString()
            .hashCode();
        // 斐波那契（Fibonacci）散列
        hashVal = (hashVal * 2654435769L) >> 28;
        // 避免hashVal超出 MAX_VALUE = 0x7fffffff时变为负数,取绝对值
        hashVal = Math.abs(hashVal) % subTableCount;
        return hashVal;
    }
}
